package com.dean.practice.consumer.ctrl;

import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author Dean
 * @date 2020-11-24
 */
@Slf4j
@RestController
@RequestMapping("/sample")
public class SampleCtrl {

    private final LoadBalancerClient loadBalancerClient;
    private final DiscoveryClient discoveryClient;
    private String defaultServiceId = "producer-service";

    @Autowired
    public SampleCtrl(LoadBalancerClient loadBalancerClient, DiscoveryClient discoveryClient) {
        this.loadBalancerClient = loadBalancerClient;
        this.discoveryClient = discoveryClient;
    }

    @Value("${spring.application.name}")
    private String serverName;

    @GetMapping("/hello")
    public String hello() {
        return "Hello : " + serverName;
    }

    @ApiOperation("获取指定服务名对应的实例列表：默认producer-service")
    @GetMapping("/services")
    public Object services(@RequestParam(value = "serviceId", required = false) String serviceId) {
        if (StringUtils.isEmpty(serviceId)) {
            serviceId = defaultServiceId;
        }
        return discoveryClient.getInstances(serviceId);
    }


    @ApiOperation("轮询实例列表获取一个实例：默认producer-service")
    @GetMapping("/discover")
    public Object discover(@RequestParam(value = "serviceId", required = false) String serviceId) {
        if (StringUtils.isEmpty(serviceId)) {
            serviceId = defaultServiceId;
        }
        return loadBalancerClient.choose(serviceId).getUri().toString();
    }

    @ApiOperation("轮询获取一个实例并执行调用：默认producer-service")
    @GetMapping("/call")
    public String call(@RequestParam(value = "serviceId", required = false) String serviceId) {
        if (StringUtils.isEmpty(serviceId)) {
            serviceId = defaultServiceId;
        }
        ServiceInstance serviceInstance = loadBalancerClient.choose(serviceId);
        return new RestTemplate().getForObject(serviceInstance.getUri().toString() + "/sample/hello", String.class);
    }
}